package com.ruoyi.wx.service.impl;


import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.CopyUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.wx.domain.PtExp;
import com.ruoyi.wx.domain.PtScore;
import com.ruoyi.wx.domain.vo.PtScoreVO;
import com.ruoyi.wx.mapper.PtExpMapper;
import com.ruoyi.wx.mapper.PtScoreMapper;
import com.ruoyi.wx.service.IPtScoreService;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author moxiu
 * @since 2021-11-13
 */
@Service
public class PtScoreServiceImpl extends ServiceImpl<PtScoreMapper, PtScore> implements IPtScoreService {

	@Autowired
	private PtExpMapper ptExpMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void createScore(Long expId, Double score) {
		//获取当前登录对象
		final SysUser user = SecurityUtils.getLoginUser().getUser();
		PtScore ptScore = baseMapper.selectExist(user.getUserId(), expId);
		if (ptScore==null) {
			throw new CustomException("视频任务没结束！无法提交预习");
		}
		List<Integer> parse = (List<Integer>) JSONObject.parse(ptScore.getVideoList());
		if (parse.size() != ptExpMapper.selectVideoSum(expId)) {
			throw new CustomException("视频任务没结束！无法提交预习");
		}
		ptScore.setPreview(score);
		ptScore.setUpdateTime(LocalDateTime.now());
		baseMapper.updateById(ptScore);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void scanCode(PtScoreVO ptScoreVO) {
		PtScore ptScore = baseMapper.selectExist(ptScoreVO.getStuId(), ptScoreVO.getExpId());
		if (ptScore == null || ptScore.getPreview() == null) {
			throw new CustomException("该同学没有完成预习任务");
		}
		//获取当前登录用户的id 就是老师id
		final Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
		ptScore.setDiscipline(ptScoreVO.getDiscipline());
		ptScore.setOperate(ptScoreVO.getOperate());
		baseMapper.updateById(ptScore);
	}
}
